<?php

namespace seecms\region;

use seecms\db\SeeDbException;
use seecms\lib\module\ModulePublish;
use seecms\region\lib\Region;
use seecms\See;

class RegionPublish extends ModulePublish
{

    protected function tableFile(): string
    {
        return dirname(__FILE__, 2) . '/database/table.sql';
    }

    /**
     * 态资源文件
     * @return bool
     */
    public function vendor(): bool
    {
        if (!class_exists('ZipArchive')) {
            return false;
        }

        $target = See::config()->vendor->root() . 'vendor' . DIRECTORY_SEPARATOR . 'region';
        if (!is_dir($target) && !mkdir($target, 0766, true)) {
            return false;
        }

        $dir = dirname(__FILE__, 2) . '/region.zip';

        $zip = new \ZipArchive();
        if (is_file($dir) && is_dir($target)) {
            if ($zip->open($dir) !== true) {
                return false;
            }
            // 解压到目标目录
            if (!$zip->extractTo($target)) {
                $zip->close();
                return false;
            }
            $zip->close();
        }

        return true;
    }

    public function init()
    {
        parent::init();

        $this->insert();
        // 保存json文件
        (new Region())->saveJson();
    }

    protected function getMenuList(): array
    {
        $data = See::db()->table('see_menu')
            ->where('parent_id', 0)
            ->where('title', '常规管理')
            ->find();

        $parent_id = 0;
        if ($data) {
            $parent_id = $data['id'] ?? '';
        }

        return [
            $this->concatMenu($parent_id, '地区管理', 'layui-icon-location', 'region/index'),
        ];
    }

    protected function getRuleList(): array
    {
        return $this->getResourceRuleList('region', '地区');
    }

    /**
     * @return bool
     */
    protected function insert(): bool
    {
        $filepath = dirname(__FILE__, 2) . '/database/region.sql';
        // 读取SQL文件
        if (!file_exists($filepath)) {
            return true;
        }

        $sql = file_get_contents($filepath);

        $queries = preprocessing_sql($sql);

        try {
            foreach ($queries as $query) {
                See::db()->query($query);
            }
        } catch (SeeDbException|\Throwable $e) {

        }

        return true;
    }
}